<template>
  <div class="login">
    <img src="../assets/logo.png" alt="" class="logo">
    <el-form :model="loginForm">
      <el-form-item label="账号" prop="email">
        <el-input  placeholder="请输入账号" v-model="loginForm.user_email"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="passwordd">
        <el-input  placeholder="请输入密码" v-model="loginForm.user_password" show-password  @keyup.enter="login"></el-input>
      </el-form-item>
      <el-form-item><router-link to="/register">还没有账号？点击注册</router-link>&emsp;<router-link to="/resetPassword">找回密码</router-link></el-form-item>
      <el-form-item>
        <el-button @click="login" class="btn_submit" type="primary">登陆</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import { ElMessage } from 'element-plus'
import { defineComponent, reactive } from 'vue'
import axios from 'axios'
import { useRouter } from 'vue-router'

export default defineComponent({
  name: 'LoginView',
  setup () {
    const router = useRouter()
    const loginForm = reactive({
      user_email: '',
      user_password: ''
    })
    const login = () => {
      if (!loginForm.user_email || !loginForm.user_password) {
        ElMessage.error('请输入账号或密码')
        return
      }
      // 判断是否全是空格或者包含空格loginForm.email.replace(/ /g, '') === '' || loginForm.passwordd.replace(/ /g, '') === ''
      if (loginForm.user_email.includes(' ') || loginForm.user_password.includes(' ')) {
        ElMessage.error('请输入正确的账号或密码')
        return
      }
      axios.post('http://localhost:8081/login', loginForm).then(res => {
        if (res.data.user_id != null) {
          console.log(res.data)
          ElMessage.success('登陆成功')
          sessionStorage.setItem('userId', res.data.user_id)
          sessionStorage.setItem('userE', res.data.user_email)
          sessionStorage.setItem('userPicture', res.data.user_picture)
          sessionStorage.setItem('user', res.data)
          router.push('/')
        } else { ElMessage.error('账号或密码错误') }
      }).catch(error => {
        console.log(error)
      })
    }
    return {
      loginForm,
      login
    }
  }
})
</script>

<style scoped>
.login{
width: 450px;
margin: 180px auto;
border: 1px solid #efefef;
padding: 20px;
border-radius: 10px;
margin-top: 60px;
}
.logo{
  margin-bottom: 20px;
}
h4{
  text-align: center;
}
.btn_submit{
  width: 100%;
}
</style>
